package com.example.api.service.impl;

import com.example.api.dao.CommodityDao;
import com.example.api.dao.InventoryDao;
import com.example.api.dao.InventoryRecordDao;
import com.example.api.model.entity.Commodity;
import com.example.api.model.entity.Inventory;
import com.example.api.model.support.RespBean;
import com.example.api.service.CommodityService;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Service
public class CommodityServiceImpl implements CommodityService {

    @Resource
    private CommodityDao commodityDao;

    @Resource
    private InventoryDao inventoryDao;

    @Resource
    private InventoryRecordDao inventoryRecordDao;

    @Override
    public RespBean save(Commodity commodity) {
        commodity.setCreateTime(new Date());
        Commodity disCommodity = commodityDao.selectByName(commodity.getName());
        if (Objects.nonNull(disCommodity)) {
            return RespBean.error("商品名称重复");
        }
        if (commodityDao.insertSelective(commodity) > 0) {
            return RespBean.success("添加成功");
        }
        return RespBean.error("添加失败");
    }

    @Override
    public RespBean update(Commodity commodity) {
        commodity.setUpdateTime(new Date());
        Commodity disCommodity = commodityDao.selectByName(commodity.getName());
        if (Objects.nonNull(disCommodity) && !commodity.getId().equals(disCommodity.getId())) {
            return RespBean.error("商品名称重复");
        }
        if (commodityDao.updateByPrimaryKeySelective(commodity) > 0) {
            inventoryDao.updateNameByCid(commodity.getName(), commodity.getId());
            inventoryRecordDao.updateNameByCid(commodity.getName(), commodity.getId());
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    @Override
    public RespBean delete(Integer id) {
        if (commodityDao.deleteByPrimaryKey(id) > 0) {
            inventoryDao.deleteByCid(id);
            inventoryRecordDao.deleteByCid(id);
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @Override
    public Commodity findById(Integer id) {
        return commodityDao.selectByPrimaryKey(id);
    }

    @Override
    public List<Commodity> findAll(String name) {
        return commodityDao.findAll(name);
    }

    @Override
    public List<Commodity> findByWid(Integer id) {
        List<Inventory> inventoryList = inventoryDao.findAllByWid(id);
        List<Commodity> commodityList = Lists.newArrayList();
        inventoryList.forEach(inventory -> {
            Commodity commodity = commodityDao.selectByPrimaryKey(inventory.getCid());
            commodityList.add(commodity);
        });
        return commodityList;
    }

}